<template>
    <el-row class="login-container" justify="center" :align="'middle'">
        <!-- <el-col :span="24" > -->
            <el-card style="max-width: 480px">
                <template #header>
                    <div class="card-header">
                        <img :src="imgUrl" alt="">
                    </div>
                </template>
                <div class="jump-link">
                    <el-link type="primary" @click="handleChange">{{ formType?'切换登录':'点击注册' }}</el-link>
                </div>
                <el-form :model="loginForm" style="max-width: 600px"
                    :rules="rules"
                    ref="loginFormRef"
                >
                    <el-form-item prop="userName">
                        <el-input v-model="loginForm.userName" placeholder="手机号" 
                        :prefix-icon="UserFilled"/>
                    </el-form-item>
                    <el-form-item prop="passWord">
                        <el-input v-model="loginForm.passWord" placeholder="密码" type="password" @keyup.enter="submitForm(loginFormRef)"
                        :prefix-icon="Lock"/>
                    </el-form-item>
                    <el-form-item prop="validCode" v-show="formType">
                        <el-input v-model="loginForm.validCode" placeholder="验证码"
                        :prefix-icon="Lock">
                        <template #append>
                            <span 
                                @click="countdownChange"
                            >{{ changeText.text }}</span>                            
                        </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submitForm(loginFormRef)">
                            {{ formType?'注册用户':'登录' }}
                        </el-button>
                    </el-form-item>
                </el-form>
            </el-card>
        <!-- </el-col> -->
  </el-row>
</template>

<script setup>
import { ref, reactive, computed, toRaw } from 'vue';
import { UserFilled, Lock } from '@element-plus/icons-vue'
import { getCode, userAuthentication, login, menuPermissions } from '../../api';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';

const router = useRouter()
const store = useStore()
const imgUrl = new URL('../../../public/login-head.png', import.meta.url).href

const routerList = computed(()=> store.state.Menu.routerList)

// 表单对象
const loginForm=reactive({
    userName:'',
    passWord:'',
    validCode:''
})


// 表单校验
// 手机号校验
const validateUser = (rule, value, callback)=>{
    if(value===''){
        callback(new Error('请输入账号'))
    }else{
        const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
        if(phoneReg.test(value))
            callback()
        else
            callback(new Error('手机号格式错误'))
    }
}
// 密码校验
const validatePass =(rule, value, callback)=>{
    if(value===''){
        callback(new Error('请输入密码'))
    }else{
        const phoneReg = /^[a-zA-Z0-9_-]{4,16}$/
        if(phoneReg.test(value))
            callback()
        else
            callback(new Error('密码格式错误'))
    }
}
// 表单校验规则
const rules=reactive({
    userName:[
        {validator: validateUser, trigger:'blur'}
        // {required: true, },
        // { required: true, message: '请输入手机号', trigger: 'blur' },
    ],
    passWord:[
        {validator: validatePass, trigger:'blur'}
    ],
    validCode:[

    ]
})
// 当前Form实例
const loginFormRef= ref()


const waitTime = 10
// 验证码相关
const changeText = reactive({
    text:'发送验证码',
    time:waitTime,
    waitting: false
})
// 验证码倒计时
const countdownChange =()=>{
    if(changeText.waitting) 
        return
    // 校验手机号
    const phoneReg = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
    if(!loginForm.userName||!phoneReg.test(loginForm.userName)){
        return ElMessage({
            message: '请检查手机号是否正确',
            type: 'warning',
        })
    }
    // 倒计时
    const timer = setInterval(() => {
        if(changeText.time>1){
            changeText.time-=1
            changeText.text=`剩余${changeText.time}s`
        }
        else{
            changeText.time =waitTime
            changeText.text='发送验证码'
            changeText.waitting = false
            clearInterval(timer)
        }
    }, 1000);
    changeText.waitting = true
    getCode({tel: loginForm.userName}).then(({data})=>{
        ElMessage.success('发送成功')
    })
}

// 切换表单 0 登录 1 注册
const formType = ref(0)
// 点击切换登录和注册
const handleChange=()=>{
    formType.value = formType.value?0:1
}

// 登录
const submitForm= async(formEl)=>{
    if(!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log(loginForm,'submit!')
            if(formType.value===0){
                // 登录
                login(loginForm).then(({data})=>{
                    console.log('login', data)
                    if(data.code===10000){
                        // ElMessage.success('登录成功')
                        ElMessage({message:'登录成功',type:'success'})
                        localStorage.setItem('pz_token', data.data.token)
                        localStorage.setItem('pz_userInfo', JSON.stringify(data.data.userInfo))

                        // 获取用户权限
                        menuPermissions().then(({data})=>{
                            // console.log(data, '用户菜单权限')
                            store.commit('dynamicMenu', data.data)
                            console.log(routerList, 'routerList')

                            toRaw(routerList.value).forEach(item=>{
                                router.addRoute('main', item)
                            })

                            router.push('/')
                        })
                    }else if(data.code===-1){
                        ElMessage.warning(data.message)
                    }
                })
            }
            else{
                // 注册
                userAuthentication(loginForm).then(({data})=>{
                    if(data.code===10000){
                        ElMessage.success('注册成功')
                        formType.value=0
                    }
                })
            }
        } else {
        console.log('error submit!', fields)
        }
    })

}
</script>

<style lang="scss" scoped>

</style>